import logging
import time

import importlib

jwt = importlib.import_module('jwt')
print("Loaded jwt from:", jwt.__file__)

import requests

from settings import SETTINGS
from record_log import record_log

# 构建请求头
def getAuthHeaders():
    """
            构建请求头
            :return:
            X-Tenant-Id：企业ID，
            X-Tenant-Type：租户类型，目前只支持 "organization" 类型，
            X-Operator-Id：操作人ID
            """
    # 配置accessToken
    tbAPPId = SETTINGS['TB_APP_ID']
    tbSecret = SETTINGS['TB_APP_SECRET']
    expire_time = int(time.time() + 3600)  # 1 小时后超时
    encoded = jwt.encode({'_appId': tbAPPId, 'exp': expire_time}, tbSecret, algorithm='HS256')
    return {'X-Operator-Id': SETTINGS['X-Operator-Id'], 'Authorization': 'Bearer ' + encoded,
            'X-Tenant-Id': SETTINGS['TB_ORG_ID'],
            'X-Tenant-Type': 'organization'}


# 创建TB项目
def create_task(content, creator, departName,note):
    record_log(f"TB创建任务内容:{creator},{departName},{content}","info")
    print('TB创建任务内容:', creator,departName,content)
    params = {
        "accomplishTime": None,
        "ancestorIds": [],
        "content": content,
        "creatorId": "62183bd4a9953fb3aafd9491",
        "customfields": [
            {
                "cfId": "6672c2351cf3502cf100b201",
                "type": "dropDown",
                "value": [
                    {
                        "id": "",
                        "title": departName
                    }
                ]
            },
            {
                "cfId": "6672c2471cf3502cf100b360",
                "type": "text",
                "value": [
                    {
                        "title": creator
                    }
                ]
            },
        ],
        "executorId": "62183bd4a9953fb3aafd9491",
        "note": note,
        "projectId": "6672bfc881ac31ea32644ff3",
        "sfcId": "6672bfc8f6f4bb8ec0bf69f6",
        "stageId": "6672bfc8f6f4bb8ec0bf69e5",
        "tasklistId": "6672bfc8f6f4bb8ec0bf69d9",
        "tfsId": "6672c0960c6915c5ddcbd577",
        "visible": "projectMembers"
    }

    # print('params: ', params)
    res = requests.post(SETTINGS["URL_TB_CREATE_TASK"], json=params, headers=getAuthHeaders())
    if res.status_code == 200:
        resJson = res.json()
        # print('resJson: ', resJson)
        return resJson.get("result")
    else:
        print(f"请求失败，状态码: {res.status_code}")
        print(f"错误响应: {res.text}")
        return None
